package com.cnpc.fyutils;

import android.app.ActivityManager;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.util.Log;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import static android.content.Context.TELEPHONY_SERVICE;

/**
 * Created by songzhiiyn on 2017-05-14.
 * 获取手机信息的工具类
 * <uses-permission android:name="android.permission.READ_PHONE_STATE" />
 */

public class PhoneUtil {

    /**
     * 获取手机基本信息
     */
    public static Map<String, String> getPhoneMessage(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        Map<String, String> map = new HashMap<>();
        map.put("mobileDeviceName",android.os.Build.BRAND);//手机设备名称
        map.put("mobileModel",android.os.Build.MODEL);//手机设备型号
        map.put("mobileOs","android");//手机操作系统
        map.put("mobileOsVersion",android.os.Build.VERSION.RELEASE);//手机操作系统版本
        if(tm.getDeviceId()!=null&&tm.getDeviceId().length()!=0){
            map.put("imei",tm.getDeviceId());//设备IMEI
        }else{
            map.put("imei","");//设备IMEI
        }
        return map;
    }
    /**
     * 获取手机基本信息
     *
     * @param context
     * @return
     */
    public static String getData(Context context) {
        String txt = "";
        TelephonyManager mTm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        txt = "手机型号：" + Build.MODEL + "\n"; // 手机型号
        txt += "SDK:" + Build.VERSION.SDK + "\n";       //  SDK版本
        txt += "Android版本:" + Build.VERSION.RELEASE + "\n";   //  系统版本号
        txt += "手机号：" + mTm.getLine1Number(); // 手机号码，有的可得，有的不可得
        return txt;
    }

    /**
     * 获取手机运行商的信息
     *
     * @param context
     * @return
     */
    public static String getProvidersName(Context context) {
        String ProvidersName = "N/A";
        TelephonyManager mTm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        try {
            String imsi = mTm.getSubscriberId();
            // IMSI号前面3位460是国家，紧接着后面2位00 02是中国移动，01是中国联通，03是中国电信。
            System.out.println(imsi);
            if (imsi.startsWith("46000") || imsi.startsWith("46002")) {
                ProvidersName = "中国移动";
            } else if (imsi.startsWith("46001")) {
                ProvidersName = "中国联通";
            } else if (imsi.startsWith("46003")) {
                ProvidersName = "中国电信";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ProvidersName;
    }

    /**
     * 获取手机MAC地址
     *
     * @param context
     * @return
     */
    public static String getMacAddress(Context context) {
        String result = "";
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        result = wifiInfo.getMacAddress();
        return result;
    }

    /**
     * 获取手机信息
     */
    public static String getPhoneInfo(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        String mtyb = Build.BRAND;// 手机品牌
        String mtype = Build.MODEL; // 手机型号
        String system_version = Build.VERSION.RELEASE; ; // Android系统版本号
        String BOOTLOADER = Build.BOOTLOADER; // 获取设备引导程序版本号
        String BOARD = Build.BOARD; // 获取设备基板名称
        String DISPLAY = Build.DISPLAY; // 获取设备显示的版本包
        String imei = tm.getDeviceId();//手机设备ID
        String txt = "";
        txt = "品牌: " + mtyb + "\n" + "型号: " + mtype + "\n"  + "Android系统版本: " + system_version
                + "\n" + "设备基板名称: " + BOARD + "\n" + "版本包: " + DISPLAY + "\n"
                + "IMEI: " + imei + "\n" + "总内存: " + getTotalMemory(context) + "\n" + "当前可用内存: " + getAvailMemory(context) + "\n"
                + "CPU名字: " + getCpuName() + "\n" + "CPU最大频率: " + getMaxCpuFreq() + "\n" + "CPU最小频率: " + getMinCpuFreq() + "\n" + "CPU当前频率: " + getCurCpuFreq() + "\n";
        return txt;
    }

    /**
     * 获取手机内存大小
     *
     * @return
     */
    public static String getTotalMemory(Context context) {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小

            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }

            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
            localBufferedReader.close();

        } catch (IOException e) {
        }
        return Formatter.formatFileSize(context, initial_memory);// Byte转换为KB或者MB，内存大小规格化
    }

    /**
     * 获取当前可用内存大小
     *
     * @return
     */
    public static String getAvailMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(context, mi.availMem);
    }

    public static String getMaxCpuFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat",
                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }
        return result.trim() + "Hz";
    }

    // 获取CPU最小频率（单位KHZ）

    public static String getMinCpuFreq() {
        String result = "";
        ProcessBuilder cmd;
        try {
            String[] args = {"/system/bin/cat",
                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq"};
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                result = result + new String(re);
            }
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = "N/A";
        }
        return result.trim() + "Hz";
    }

    // 实时获取CPU当前频率（单位KHZ）

    public static String getCurCpuFreq() {
        String result = "N/A";
        try {
            FileReader fr = new FileReader(
                    "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
            BufferedReader br = new BufferedReader(fr);
            String text = br.readLine();
            result = text.trim() + "Hz";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String getCpuName() {
        try {
            FileReader fr = new FileReader("/proc/cpuinfo");
            BufferedReader br = new BufferedReader(fr);
            String text = br.readLine();
            String[] array = text.split(":\\s+", 2);
            for (int i = 0; i < array.length; i++) {
            }
            return array[1];
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
